package com.longrise.co.ui.carfiles.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.compress.CompressConfig;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.LubanOptions;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TImage;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.model.TakePhotoOptions;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.longrise.co.R;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carfiles.adapter.UploadPhotoAdapter;
import com.longrise.co.ui.carfiles.contract.CarFilesContract;
import com.longrise.co.ui.carfiles.model.CarFilesModel;
import com.longrise.co.ui.carfiles.model.RxRepairRecordBean;
import com.longrise.co.ui.carfiles.model.UploadBean;
import com.longrise.co.ui.carfiles.model.UploadPhotoBean;
import com.longrise.co.ui.carfiles.presenter.CarFilesPresenter;
import com.longrise.co.ui.carfiles.widget.AddPhotoDialog;
import com.longrise.co.ui.carfiles.widget.ComplaintSuccessDialog;
import com.longrise.co.ui.carfiles.widget.RealNameDialog;
import com.longrise.co.ui.home.model.CompanyDetail;
import com.longrise.co.ui.mine.fragment.VerifiedFragment;
import com.longrise.co.utils.Constants;
import com.longrise.co.utils.StringUtils;
import com.ly.common.base.BaseFragment;
import com.ly.common.dialog.DialogOnClickListener;
import com.ly.common.dialog.MDAlertDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by luoyang on 2017-7-17.
 */

public class RepairComplaintFragment extends BaseFragment<CarFilesPresenter, CarFilesModel> implements CarFilesContract.ComplaintView<CompanyDetail>, BaseQuickAdapter.OnRecyclerViewItemClickListener,TakePhoto.TakeResultListener,InvokeListener, AddPhotoDialog.OnSelectPhotoListener, DialogOnClickListener {

    @Bind(R.id.head_title)
    TextView headTitle;
    @Bind(R.id.complaint_location_tv)
    TextView complaintLocationTv;
    @Bind(R.id.complaint_call_tv)
    TextView complaintCallTv;
    @Bind(R.id.complaint_reason)
    EditText complaintReason;
    @Bind(R.id.upload)
    RecyclerView upload;
    @Bind(R.id.complaint_name)
    TextView complaintName;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;

    private String mCompanyId;
    private String mRecordId;
    private String mYear;
    private String mAreaId;

    private UploadPhotoAdapter mAdapter;
    private RealNameDialog mDialog;
    private AddPhotoDialog mAddPhotoDialog;
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private Uri imageUri;

    private TImage mCurrentImage;
    //上传图片最大数
    private static final int MAX_UPLOAD_IMAGE = 5;

    private StringBuffer jsonArray = new StringBuffer();

    private ComplaintSuccessDialog mComplaintDialog;
    private MDAlertDialog mCallDialog;

    private CompanyDetail mData;

    @Override
    protected int getLayoutResource() {
        return R.layout.fg_repair_complaint;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        setText(headTitle, "维修投诉");
        initRecyclerView();
        initPhotoSelect();
        mCompanyId = getArguments().getString("companyId");
        mRecordId = getArguments().getString("recordId");
        mYear = getArguments().getString("year");
        mAreaId = getArguments().getString("areaId");

        jsonArray.append("[");
        mPresenter.getCompanyDetail(mCompanyId);

    }

    private void initPhotoSelect() {
//        configCompress();
        configTakePhotoOption();
    }

    private void configCompress(){
        LubanOptions option=new LubanOptions.Builder()
                .setMaxHeight(800)
                .setMaxWidth(800)
                .setMaxSize(200*1024)
                .create();
        CompressConfig config=CompressConfig.ofLuban(option);
        config.enableReserveRaw(false);
        takePhoto.onEnableCompress(config, false);
    }

    private void configTakePhotoOption(){
        TakePhotoOptions.Builder builder=new TakePhotoOptions.Builder();
        builder.setWithOwnGallery(true);
        builder.setCorrectImage(false);
        takePhoto.setTakePhotoOptions(builder.create());

    }

    private void initRealNameDialog() {
        mDialog = new RealNameDialog(getContext(), R.style.dialog_style);
        mDialog.setCanceledOnTouchOutside(true);
        mDialog.setOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                start(VerifiedFragment.newInstance());
                mDialog.dismiss();
            }
        });
        mDialog.create();
    }

    private void initAddPhotoDialog() {
        mAddPhotoDialog = new AddPhotoDialog(getContext(), R.style.dialog_style);
        mAddPhotoDialog.setCanceledOnTouchOutside(true);
        mAddPhotoDialog.setOnSelectPhotoListener(this);
        mAddPhotoDialog.show();

    }

    private void initRecyclerView() {
        List<UploadPhotoBean> list = new ArrayList<>();
        list.add(new UploadPhotoBean(Constants.UPLOAD_TYPE_TWO, String.valueOf(MAX_UPLOAD_IMAGE)));

        GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 3);
        upload.setLayoutManager(layoutManager);
        mAdapter = new UploadPhotoAdapter(getContext(), list);

        mAdapter.openLoadMore(false);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        upload.setAdapter(mAdapter);
    }

    @Override
    public void requestSuccess(CompanyDetail companyDetail) {
        if(companyDetail == null) {
            return;
        }
        mData = companyDetail;
        setText(complaintName, companyDetail.getCompanyname());
        if(!StringUtils.isEmpty(companyDetail.getStar())) {
            ratingBar.setRating(Float.parseFloat(companyDetail.getStar()));
        }

        setText(complaintLocationTv, companyDetail.getCompanyaddress());
        setText(complaintCallTv, companyDetail.getBusphone());

    }

    @Override
    public void onComplete() {

    }

    public static RepairComplaintFragment newInstance(String companyId, String recordId, String year, String areaId) {

        Bundle args = new Bundle();
        args.putString("companyId", companyId);
        args.putString("recordId", recordId);
        args.putString("year", year);
        args.putString("areaId", areaId);
        RepairComplaintFragment fragment = new RepairComplaintFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private void initCallDialog() {
        mCallDialog = new MDAlertDialog.Builder(getContext())
                .setContentText("确定拨打该企业电话？")
                .setOnclickListener(this)
                .build();
    }

    @OnClick({R.id.head_back, R.id.submit,R.id.complaint_call_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.head_back:
                _mActivity.onBackPressed();
                break;
            case R.id.complaint_call_iv:
                if(mCallDialog == null) {
                    initCallDialog();
                }
                mCallDialog.show();
                break;
            case R.id.submit:
              /*  if(mDialog == null) {
                    initRealNameDialog();
                }
                mDialog.show();*/
              if(com.ly.common.commonutils.StringUtils.isEmpty(complaintReason.getText().toString())) {
                  showLongToast("请输入投诉内容");
                  return;
              }

              //判断是否已认证
                if(!CommonPara.getInstance().isAuthStatus()) {
                    if(mDialog == null) {
                        initRealNameDialog();
                    }
                    mDialog.show();
                    return;
                }
              if(jsonArray != null) {
                  String json = jsonArray.substring(0, jsonArray.length() - 1 ) + "]";
                  Log.i("json", json);
                  mPresenter.carComplaint(mRecordId, mYear, complaintReason.getText().toString(), json);
              }
                break;
        }
    }

    @Override
    public void clickLeftButton(View view) {
        if(mCallDialog != null) {
            mCallDialog.dismiss();
        }
    }

    @Override
    public void clickRightButton(View view) {

        //拨打电话
        if(mData != null && !StringUtils.isEmpty(mData.getBusphone())) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + mData.getBusphone()));
            startActivity(intent);
        }

        if(mCallDialog != null) {
            mCallDialog.dismiss();
        }
    }

    private void initDialog() {
        mComplaintDialog = new ComplaintSuccessDialog(getContext(), R.style.dialog_style);
        mComplaintDialog.setCanceledOnTouchOutside(false);
        mComplaintDialog.setOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mComplaintDialog.dismiss();
                //返回上一层
                _mActivity.onBackPressed();
            }
        });
    }

    @Override
    public void submitSuccess() {
        mRxManager.post(Constants.RX_EVENT_REPAIR_RECORD, new RxRepairRecordBean("4", null));
        mRxManager.post(Constants.RX_EVENT_REFRESH_MINE, null);
        if(mComplaintDialog == null) {
            initDialog();
        }
        mComplaintDialog.show();
    }

    @Override
    public void takeSuccess(TResult result) {
        try {
            if(result != null && result.getImage() != null) {
                mCurrentImage = result.getImage();
//                String imageInfo = ImageUtils.bitmapToString( );
                String imageInfo = StringUtils.File2Base64(result.getImage().getOriginalPath());
                mPresenter.uploadPhoto(imageInfo, "5");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void uploadPhotoSuccess(UploadBean bean) {
        showLongToast("上传图片成功!");
        List<UploadPhotoBean> list = new ArrayList<>();
        list.addAll(mAdapter.getData());
        int last = list.size() - 1 ;
        list.remove(last);
        list.add(new UploadPhotoBean(Constants.UPLOAD_TYPE_ONE, mCurrentImage.getOriginalPath()));

        int size = list.size();
        if(size < MAX_UPLOAD_IMAGE) {
            list.add(new UploadPhotoBean(Constants.UPLOAD_TYPE_TWO, String.valueOf(MAX_UPLOAD_IMAGE - size)));
        }
        jsonArray.append(bean.getImagedata())
                .append(",");
        mAdapter.setNewData(list);


    }


    @Override
    public void onItemClick(View view, int i) {
        UploadPhotoBean bean = (UploadPhotoBean)mAdapter.getData().get(i);
        if(Constants.UPLOAD_TYPE_ONE == bean.getItemType()) {
            //点击照片

        } else if(Constants.UPLOAD_TYPE_TWO == bean.getItemType()) {
            //上传照片
            if(mAddPhotoDialog == null) {
                initAddPhotoDialog();
            }
            mAddPhotoDialog.show();
//            takePhoto.onPickFromGallery();

        }
    }

    /**
     *  获取TakePhoto实例
     * @return
     */
    public TakePhoto getTakePhoto(){
        if (takePhoto==null){
            takePhoto= (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this,this));
        }
        return takePhoto;
    }




    @Override
    public void takeFail(TResult result, String msg) {
        showErrorTip(msg);
    }

    @Override
    public void takeCancel() {

    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type=PermissionManager.onRequestPermissionsResult(requestCode,permissions,grantResults);
        PermissionManager.handlePermissionsResult(getActivity(),type,invokeParam,this);
    }


    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type=PermissionManager.checkPermission(TContextWrap.of(this),invokeParam.getMethod());
        if(PermissionManager.TPermissionType.WAIT.equals(type)){
            this.invokeParam=invokeParam;
        }
        return type;
    }

    @Override
    public void onSelect(int type) {
        switch (type) {
            case AddPhotoDialog.SELECT_ALBUM :
                //选择相册
                takePhoto.onPickFromGallery();
//                        onPickMultiple(MAX_UPLOAD_IMAGE + 1 - mAdapter.getData().size());
                break;
            case AddPhotoDialog.SELECT_PHOTO :
                //拍照
                File file=new File(Environment.getExternalStorageDirectory(), "/temp/"+System.currentTimeMillis() + ".jpg");
                if (!file.getParentFile().exists())file.getParentFile().mkdirs();
                imageUri = Uri.fromFile(file);
                if(imageUri != null) {
                    takePhoto.onPickFromCapture(imageUri);
                }
                break;
            case AddPhotoDialog.SELECT_CANCEL :
                break;
        }
        mAddPhotoDialog.dismiss();
    }

}
